<script setup>
import { ref, onMounted } from 'vue'
import { formatDateTime } from '@/utils/dayjs'
import { submitSettlement } from '@/api/goodsSettle'
import { getBankList } from '@/api/bank'
import { getBankInfoByCardNumber } from '@/constants/bank'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
})

const emit = defineEmits(['close', 'success'])
const loading = ref(false)
const bankList = ref([])
const selectedBankId = ref(null)

const fetchBankList = async () => {
  try {
    const res = await getBankList()
    if (res.success) {
      bankList.value = res.data.filter((i) => i.status === 0) || []
    } else {
      ElMessage.error(res.msg || '获取银行列表失败')
    }
  } catch (error) {
    logger.error('获取银行列表失败', error)
    ElMessage.error('获取银行列表失败')
  }
}

onMounted(() => {
  fetchBankList()
})

const handleSubmit = async () => {
  if (!selectedBankId.value) {
    ElMessage.warning('请选择结款银行账户')
    return
  }
  try {
    loading.value = true
    const payload = {
      ...props.data,
      dealerBankId: selectedBankId.value,
    }
    const res = await submitSettlement(payload)
    if (res.success) {
      ElMessage.success('提交结算申请成功')
      emit('success')
    } else {
      ElMessage.error(res.msg || '提交结算申请失败')
    }
  } catch (error) {
    logger.error('提交结算申请失败', error)
    ElMessage.error('提交结算申请失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  emit('close')
}
</script>
<template>
  <div class="settlement-note">
    <h2 class="title">结算申请单详情</h2>
    <div class="settlement-info">
      <el-descriptions title="结算信息" :column="3" border>
        <el-descriptions-item label="单据号">{{ data.documentNumber }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{
          formatDateTime(data.requestTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ data.nickname }}</el-descriptions-item>
        <el-descriptions-item label="总结算积分">{{
          data.settlementPointsSum
        }}</el-descriptions-item>
        <el-descriptions-item label="总结算金额(元)">{{
          data.settlementAmountSum
        }}</el-descriptions-item>
      </el-descriptions>
      <div class="bank-selection">
        <span class="label required">结款银行:</span>
        <el-select v-model="selectedBankId" placeholder="请选择结款银行账户" style="width: 100%">
          <el-option
            v-for="bank in bankList"
            :key="bank.dealerBankId"
            :label="`${bank.bankName} - ${bank.bankCode}`"
            :value="bank.dealerBankId"
          >
            <div class="bank-option">
              <img
                v-if="getBankInfoByCardNumber(bank.bankCode).logo"
                :src="getBankInfoByCardNumber(bank.bankCode).logo"
                alt="logo"
                class="bank-logo-small"
              />
              <span class="bank-name">{{ bank.bankName }}</span>
              <span class="bank-code">{{ bank.bankCode }}</span>
            </div>
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="goods-list">
      <h3>商品列表</h3>
      <el-table :data="data.pzPointsSettlementDList" style="width: 100%" height="100%">
        <el-table-column prop="goodsName" label="商品名称" min-width="180" />
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="{ row }">
            <el-image
              style="width: 80px; height: 80px"
              :src="row.goodsPicture"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column prop="dealerGoodsTypeName" label="商品类型" min-width="120" />
        <el-table-column prop="specifications" label="规格" min-width="100" />
        <el-table-column prop="purchaseQuantity" label="采购数量" min-width="80" />
        <el-table-column prop="settlementPoints" label="结算积分" min-width="100" />
        <el-table-column prop="settlementAmount" label="结算金额(元)" min-width="120" />
      </el-table>
    </div>

    <div class="actions">
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        <template #icon>
          <el-icon><LineMdPlus /></el-icon>
        </template>
        提交</el-button
      >

      <el-button @click="handleCancel">
        <template #icon>
          <el-icon><LineMdClose /></el-icon> </template
        >取消</el-button
      >
    </div>
  </div>
</template>
<style lang="scss" scoped>
.settlement-note {
  height: 80vh;
  display: flex;
  flex-direction: column;
  .title {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}

.settlement-info,
.goods-list {
  margin-top: 20px;
}

.goods-list {
  flex: 1;
  min-height: 0; // 关键，防止flex子项溢出
  overflow: auto;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
}

.bank-selection {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  .label {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    flex-shrink: 0;
    width: 90px;
    text-align: right;
    padding-right: 12px;
    &.required::before {
      content: '*';
      color: var(--el-color-danger);
      margin-right: 4px;
    }
  }
}

.bank-option {
  display: flex;
  align-items: center;
  gap: 8px;
  .bank-logo-small {
    width: 24px;
    height: 24px;
    border-radius: 50%;
  }
  .bank-name {
    font-weight: 500;
  }
  .bank-code {
    color: #909399;
    font-size: 12px;
  }
}

.actions {
  margin-top: 20px;
  text-align: right;
}
</style>
